import Vue from 'vue'
import VueRouter from 'vue-router'

import login from '../views/login.vue'
// @:表示src的绝对路径,用它可能会导致最后一级没有提示,需要格外小心
import register from '@/views/register.vue'
import layout from '../views/layout.vue'
import detail from '../views/detail.vue'

import like from '@/views/layout/like'
import article from '@/views/layout/article'
import collect from '@/views/layout/collect'
import user from '@/views/layout/user'
import { getToken } from '@/utils/storage'
import ArticleItem from '@/components/article-item.vue'
Vue.use(VueRouter)

const routes = [
  // {
  //   path: '/',
  //   redirect: 'layout'
  // },
  { path: '/login', component: login },
  { path: '/register', component: register },
  {
    path: '/',
    component: layout,
    redirect: 'article',
    children: [
      { path: '/article', component: article },
      { path: '/like', component: like },
      { path: '/collect', component: collect },
      { path: '/user', component: user }
    ]
  },
  { path: '/detail', component: detail }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register'] // 白名单列表，记录无需权限访问的所有页面

router.beforeEach((to, from, next) => {
  const token = getToken()
  // 如果有token，直接放行
  if (token) {
    next()
  } else {
    // 没有token的人, 看看你要去哪
    // (1) 访问的是无需授权的页面（白名单），也是放行
    //     就是判断，访问的地址，是否在白名单数组中存在 includes
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // (2) 否则拦截到登录
      next('/login')
    }
  }
})
Vue.component('ArticleItem', ArticleItem)

export default router
